package com.xz.message.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.core.domain.entity.SysDept;
import com.xz.common.core.domain.entity.SysUser;
import com.xz.common.utils.SecurityUtils;
import com.xz.message.domain.Sms;
import com.xz.message.domain.SysTenantNotifyConfig;
import com.xz.message.domain.SysTenantNotifyItem;
import com.xz.message.mapper.SmsMapper;
import com.xz.message.mapper.SysTenantNotifyConfigMapper;
import com.xz.message.mapper.SysTenantNotifyItemMapper;
import com.xz.message.service.ISysTenantNotifyItemService;
import com.xz.message.service.ISysTenantNotifyParamService;
import com.xz.message.utils.DdapiUtil;
import com.xz.message.utils.QyapiUtil;
import com.xz.message.vo.*;
import com.xz.process.domain.ProcessOrder;
import com.xz.system.domain.SysTenantConfig;
import com.xz.system.mapper.SysTenantMapper;
import com.xz.system.service.ISysConfigService;
import com.xz.system.service.ISysDeptService;
import com.xz.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 消息模板配置Service业务层处理
 *
 * @author xz
 */
@Service
public class SysTenantNotifyItemServiceImpl extends ServiceImpl<SysTenantNotifyItemMapper, SysTenantNotifyItem> implements ISysTenantNotifyItemService {
    @Autowired
    private SysTenantNotifyItemMapper sysTenantNotifyItemMapper;
    @Autowired
    private SysTenantNotifyConfigMapper sysTenantNotifyConfigMapper;
    @Autowired
    private SysTenantMapper sysTenantMapper;
    @Autowired
    private SmsMapper smsMapper;
    @Autowired
    private QyapiUtil qyapiUtil;
    @Autowired
    private DdapiUtil ddapiUtil;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Resource
    private SendMsgCommonInterfaceServiceImpl sendMessageZZService;
    @Autowired
    private ISysConfigService iSysConfigService;
    @Autowired
    private ISysTenantNotifyParamService sysTenantNotifyParamService;

    @Override
    public List<SysTenantNotifyItem> selectListByType() {
        List<Integer> typeList = new ArrayList<>();
        Collections.addAll(typeList, 8, 9, 10, 11);
        List<SysTenantNotifyItem> sysTenantNotifyItems = baseMapper.selectListByType(typeList);
        return sysTenantNotifyItems;
    }

    @Override
    public String selecContexttByType(Integer msgType) {
        List<Integer> typeList = new ArrayList<>();
        typeList.add(msgType);
        List<SysTenantNotifyItem> sysTenantNotifyItems = baseMapper.selectListByType(typeList);

        String context = "";
        if(!CollectionUtils.isEmpty(sysTenantNotifyItems)){
            SysTenantNotifyItem item = sysTenantNotifyItems.get(0);
            if(null != item && StringUtils.isNotEmpty( item.getMsgContent())){
                context = item.getMsgContent();
            }
        }
        return context;
    }

    /**
     * 查询消息模板配置
     *
     * @return 消息模板配置
     */
    @Override
    public TempLateVO selectSysTenantNotifyItemByTenantId(Long tenantId) {
        SysTenantNotifyItem sysTenantNotifyItem = new SysTenantNotifyItem();
        sysTenantNotifyItem.setTenantId(tenantId);

        List<SysTenantNotifyItem> sysTenantNotifyItems = sysTenantNotifyItemMapper.selectSysTenantNotifyItemList(sysTenantNotifyItem);
        SysTenantNotifyConfig sysTenantNotifyConfig = sysTenantNotifyConfigMapper.selectNotifyConfigByTenantId(tenantId);
        SysTenantConfig sysTenantConfig = sysTenantMapper.selectSysTenantConfigById(tenantId);

        TempLateVO tempLateVO = new TempLateVO();
        if(Objects.nonNull(sysTenantNotifyConfig)) {
            tempLateVO.setQyEnable(sysTenantNotifyConfig.getQyEnable());
            tempLateVO.setDdEnable(sysTenantNotifyConfig.getDdEnable());
            tempLateVO.setDxEnable(sysTenantNotifyConfig.getDxEnable());
            tempLateVO.setNearPickTimeStaff(sysTenantNotifyConfig.getNearPickTimeStaff());
            tempLateVO.setNearReturnTimeStaff(sysTenantNotifyConfig.getNearReturnTimeStaff());
            tempLateVO.setNearPickTimeCustomer(sysTenantNotifyConfig.getNearPickTimeCustomer());
            tempLateVO.setNearReturnTimeCustomer(sysTenantNotifyConfig.getNearReturnTimeCustomer());
            Map<Integer, List<SysTenantNotifyItem>> collect = sysTenantNotifyItems.stream().collect(Collectors.groupingBy(SysTenantNotifyItem::getMsgType));
            //会员余额变动通知
            List<SysTenantNotifyItem> list0 = Optional.ofNullable(collect.get(0)).orElse(new ArrayList<>());

            TempLateItem tempLateItem8 = new TempLateItem(list0);
            List<SysTenantNotifyItem> list1 = collect.get(1);
            if (Objects.nonNull(list1) && !list1.isEmpty()) {
                tempLateItem8.setContent1(list1.get(0).getMsgContent());
            }
            List<SysTenantNotifyItem> list2 = collect.get(2);
            if (Objects.nonNull(list2) && !list2.isEmpty()) {
                tempLateItem8.setContent2(list2.get(0).getMsgContent());
            }
            List<SysTenantNotifyItem> list3 = collect.get(3);
            if (Objects.nonNull(list3) && !list3.isEmpty()) {
                tempLateItem8.setContent3(list3.get(0).getMsgContent());
            }
            List<SysTenantNotifyItem> list4 = collect.get(4);
            if (Objects.nonNull(list4) && !list4.isEmpty()) {
                tempLateItem8.setContent4(list4.get(0).getMsgContent());
            }
            List<SysTenantNotifyItem> list5 = collect.get(5);
            if (Objects.nonNull(list5) && !list5.isEmpty()) {
                tempLateItem8.setContent5(list5.get(0).getMsgContent());
            }
            tempLateVO.setTemplate8(tempLateItem8);

            //加工中心通知客户寄送镜框、成品已邮寄
            List<SysTenantNotifyItem> list6 = Optional.ofNullable(collect.get(6)).orElse(new ArrayList<>());
            TempLateItem tempLateItem9 = new TempLateItem(list6);
            List<SysTenantNotifyItem> list7 = collect.get(7);
            if (Objects.nonNull(list7) && !list7.isEmpty()) {
                tempLateItem9.setContent1(list7.get(0).getMsgContent());
            }
            tempLateVO.setTemplate9(tempLateItem9);

            //患者管理的营销短信
            List<SysTenantNotifyItem> list8 = Optional.ofNullable(collect.get(8)).orElse(new ArrayList<>());
            TempLateItem tempLateItem1 = new TempLateItem(list8);
            List<SysTenantNotifyItem> list9 = collect.get(9);
            if (Objects.nonNull(list9) && !list9.isEmpty()) {
                tempLateItem1.setContent1(list9.get(0).getMsgContent());
            }
            List<SysTenantNotifyItem> list10 = collect.get(10);
            if (Objects.nonNull(list10) && !list10.isEmpty()) {
                tempLateItem1.setContent2(list10.get(0).getMsgContent());
            }
            List<SysTenantNotifyItem> list11 = collect.get(11);
            if (Objects.nonNull(list11) && !list11.isEmpty()) {
                tempLateItem1.setContent3(list11.get(0).getMsgContent());
            }
            tempLateVO.setTemplate1(tempLateItem1);
        }
        return tempLateVO;
    }

    /**
     * 修改消息模板配置
     *
     * @param tempLateVO 消息模板配置
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateSysTenantNotifyItem(TempLateVO tempLateVO) {
        Long tenantId = Objects.requireNonNull(SecurityUtils.getLoginUser()).getTenantId();
        sysTenantNotifyItemMapper.deleteSysTenantNotifyItemByTenantId(tenantId);

        SysTenantNotifyConfig sysTenantNotifyConfig = sysTenantNotifyConfigMapper.selectNotifyConfigByTenantId(tenantId);
        sysTenantNotifyConfig.setQyEnable(tempLateVO.getQyEnable());
        sysTenantNotifyConfig.setDdEnable(tempLateVO.getDdEnable());
        sysTenantNotifyConfig.setDxEnable(tempLateVO.getDxEnable());
        sysTenantNotifyConfig.setNearPickTimeStaff(tempLateVO.getNearPickTimeStaff());
        sysTenantNotifyConfig.setNearReturnTimeStaff(tempLateVO.getNearReturnTimeStaff());
        sysTenantNotifyConfig.setNearPickTimeCustomer(tempLateVO.getNearPickTimeCustomer());
        sysTenantNotifyConfig.setNearReturnTimeCustomer(tempLateVO.getNearReturnTimeCustomer());
        sysTenantNotifyConfigMapper.updateSysTenantNotifyConfig(sysTenantNotifyConfig);

        List<SysTenantNotifyItem> list = new ArrayList<>();
        TempLateItem template1 = tempLateVO.getTemplate1();
        if(StringUtils.isNotBlank(template1.getContent0())){
            list.add(dataSysTenantNotifyItem(tenantId,template1.getContent0(),8));
        }
        if(StringUtils.isNotBlank(template1.getContent1())){
            list.add(dataSysTenantNotifyItem(tenantId,template1.getContent1(),9));
        }
        if(StringUtils.isNotBlank(template1.getContent2())){
            list.add(dataSysTenantNotifyItem(tenantId,template1.getContent2(),10));
        }
        if(StringUtils.isNotBlank(template1.getContent3())){
            list.add(dataSysTenantNotifyItem(tenantId,template1.getContent3(),11));
        }

        TempLateItem template8 = tempLateVO.getTemplate8();
        if(StringUtils.isNotBlank(template8.getContent0())){
            list.add(dataSysTenantNotifyItem(tenantId,template8.getContent0(),0));
        }
        if(StringUtils.isNotBlank(template8.getContent1())){
            list.add(dataSysTenantNotifyItem(tenantId,template8.getContent1(),1));
        }
        if(StringUtils.isNotBlank(template8.getContent2())){
            list.add(dataSysTenantNotifyItem(tenantId,template8.getContent2(),2));
        }
        if(StringUtils.isNotBlank(template8.getContent3())){
            list.add(dataSysTenantNotifyItem(tenantId,template8.getContent3(),3));
        }
        if(StringUtils.isNotBlank(template8.getContent4())){
            list.add(dataSysTenantNotifyItem(tenantId,template8.getContent4(),4));
        }
        if(StringUtils.isNotBlank(template8.getContent5())){
            list.add(dataSysTenantNotifyItem(tenantId,template8.getContent5(),5));
        }
        TempLateItem template9 = tempLateVO.getTemplate9();
        if(StringUtils.isNotBlank(template9.getContent0())){
            list.add(dataSysTenantNotifyItem(tenantId,template9.getContent0(),6));
        }
        if(StringUtils.isNotBlank(template9.getContent1())){
            list.add(dataSysTenantNotifyItem(tenantId,template9.getContent1(),7));
        }
        return saveBatch(list);
    }

    /**
     * 数据处理
     * @param tenantId
     * @param content
     * @param msgType
     * @return
     */
    public SysTenantNotifyItem  dataSysTenantNotifyItem(Long tenantId,String content,Integer msgType){
        SysTenantNotifyItem item=new SysTenantNotifyItem();
        item.setTenantId(tenantId);
        item.setMsgContent(content);
        item.setMsgType(msgType);
        return item;
    }

    /**
     * 会员余额变动通知
     * @param info
     * @param msgTypes
     *   0会员钱包充值
     *   1会员钱包消费
     *   2会员钱包消费退款
     *   3会员钱包退款
     *   4会员钱包绑定患者
     *   5会员钱包解绑患者
     * @param sysUser
     */
    @Override
    public void sendMemberInfoMsg(MemberMsgInfo info, Integer msgTypes, SysUser sysUser) {

        SysDept sysDept = sysDeptService.selectDeptById(info.getDeptId());
        if(null == sysDept){
            return;
        }
        // 金额字段都需要保留两位小数
        final BigDecimal variableAmount = info.getVariableAmount();
        if(null != variableAmount){
            info.setVariableAmount(variableAmount.setScale(2));
        }
        final BigDecimal walletBalance = info.getWalletBalance();
        if(null != walletBalance){
            info.setWalletBalance(walletBalance.setScale(2));
        }
	    System.out.println(JSONObject.toJSONString(info));
        info.setStorePhone(sysDept.getPhone());
        info.setOperateStores(sysDept.getDeptName());
        Map<String, String> param = sysTenantNotifyParamService.getForMember(info, msgTypes);
        SysTenantConfig sysTenantConfig = sysTenantMapper.selectSysTenantConfigById(info.getTenantId());
        //消息模板
        SysTenantNotifyItem sysTenantNotifyItem = new SysTenantNotifyItem();
        sysTenantNotifyItem.setMsgType(msgTypes);
        sysTenantNotifyItem.setTenantId(info.getTenantId());
        List<SysTenantNotifyItem> sysTenantNotifyItems = sysTenantNotifyItemMapper.selectSysTenantNotifyItemList(sysTenantNotifyItem);
        if(!CollectionUtils.isEmpty(sysTenantNotifyItems)){
            sendStaffMsg(param, sysTenantConfig, sysTenantNotifyItems.get(0), sysUser,info.getPhoneNumber(), info.getId()+"");
        }
    }

    @Override
    public void sendListMemberInfoMsg(List<MemberMsgInfo> infos, Integer msgTypes, SysUser sysUser){

        for (MemberMsgInfo info:infos) {
            Map<String, String> param = sysTenantNotifyParamService.getForMember(info, msgTypes);
            SysTenantConfig sysTenantConfig = sysTenantMapper.selectSysTenantConfigById(info.getTenantId());
            //消息模板
            SysTenantNotifyItem sysTenantNotifyItem = new SysTenantNotifyItem();
            sysTenantNotifyItem.setMsgType(msgTypes);
            sysTenantNotifyItem.setTenantId(info.getTenantId());
            List<SysTenantNotifyItem> sysTenantNotifyItems = sysTenantNotifyItemMapper.selectSysTenantNotifyItemList(sysTenantNotifyItem);
            if(!CollectionUtils.isEmpty(sysTenantNotifyItems)){
                sendStaffMsg(param, sysTenantConfig, sysTenantNotifyItems.get(0), sysUser,info.getPhoneNumber(), info.getId()+"");
            }
        }
    }

    /**
     * 加工中心通知客户寄送镜框、成品已邮寄
     * @param processOrder
     * @param msgTypes
     */
    public void sendMachiningCenterMsg(ProcessOrder processOrder, Integer msgTypes, SysUser sysUser) {

        Map<String, String> param = sysTenantNotifyParamService.getForProcessOrder(processOrder, msgTypes);
        SysTenantConfig sysTenantConfig = sysTenantMapper.selectSysTenantConfigById(processOrder.getTenantId());
        //消息模板
        SysTenantNotifyItem sysTenantNotifyItem = new SysTenantNotifyItem();
        sysTenantNotifyItem.setMsgType(msgTypes);
        sysTenantNotifyItem.setTenantId(processOrder.getTenantId());
        List<SysTenantNotifyItem> sysTenantNotifyItems =
                sysTenantNotifyItemMapper.selectSysTenantNotifyItemList(sysTenantNotifyItem);
        if (!CollectionUtils.isEmpty(sysTenantNotifyItems)) {
            sendStaffMsg(param, sysTenantConfig, sysTenantNotifyItems.get(0), sysUser, processOrder.getPatientPhone()
                    , processOrder.getId() + "");
        }
    }

    /**
     * 发送短信
     * @param param
     * @param sysTenantConfig
     * @param sysTenantNotifyItems
     * @param sysUser
     * @param phone
     * @param bizNo
     */
    public void sendStaffMsg(Map<String, String> param, SysTenantConfig sysTenantConfig,  SysTenantNotifyItem sysTenantNotifyItems, SysUser sysUser,String phone, String bizNo) {
        String sendMsg = sysTenantNotifyParamService.replaceTplContent(sysTenantNotifyItems.getMsgContent(), param);
        try {
            // 留一个后门，当含有该字符标识的模板，不发送短消息,只记录日志。
            // 目的是应对异常状况；便于生产环境下，临时关闭该模板短信发送，或者调试模板。
            if(sendMsg.startsWith("【禁用!】")){
                insertDxSms(sendMsg, false, String.valueOf(sysUser.getUserId()),
                        sysUser.getUserName(), sysTenantConfig.getTenantId(), sysTenantNotifyItems.getMsgType(), bizNo);
                return;
            }
            boolean msgFlag = sendMessageZZService.sendBuinessMsgPost(phone, sendMsg, sysTenantConfig.getSmsId(),sysTenantConfig.getSmsPsw());
            insertDxSms(sendMsg, msgFlag, String.valueOf(sysUser.getUserId()), sysUser.getUserName(),
                    sysTenantConfig.getTenantId(), sysTenantNotifyItems.getMsgType(), bizNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //企微单人通知
    private void insertQwDrSms(SysTenantNotifyItem item, String sendMsg, MessageResponse messageResponse, String bizNo) {
        Sms sms = new Sms();
        sms.setContent(sendMsg);
        sms.setStatus(messageResponse.getErrcode() == 0 ? "0" : "1");
        sms.setTemplateId(1L);
        sms.setSendTime(new Date());
        sms.setCustomerId(item.getPushStaff());
        sms.setCustomerName(item.getPushStaffName());
        sms.setTenantId(item.getTenantId());
        sms.setPushNode(item.getMsgType());
        sms.setRemark(messageResponse.getErrmsg());
        smsMapper.insertSms(sms);
    }

    //企微群通知
    private void insertQwQunSms(SysTenantNotifyItem item, String sendMsg, String status, String remark, String bizNo) {
        Sms sms = new Sms();
        sms.setContent(sendMsg);
        sms.setStatus(status);
        sms.setTemplateId(4L);
        sms.setSendTime(new Date());
        sms.setCustomerName(item.getQyWebhook());
        sms.setTenantId(item.getTenantId());
        sms.setPushNode(item.getMsgType());
        sms.setRemark(remark);
        sms.setBizNo(bizNo);
        smsMapper.insertSms(sms);
    }

    //钉钉单人通知
    private void insertDdDrSms(SysTenantNotifyItem item, String sendMsg, DingDingMessageResponse messageResponse, String bizNo) {
        Sms sms = new Sms();
        sms.setContent(sendMsg);
        sms.setStatus(messageResponse.getErrcode() == 0 ? "0" : "1");
        sms.setTemplateId(2L);
        sms.setSendTime(new Date());
        sms.setCustomerId(item.getPushStaff());
        sms.setCustomerName(item.getPushStaffName());
        sms.setTenantId(item.getTenantId());
        sms.setPushNode(item.getMsgType());
        sms.setRemark(messageResponse.getErrmsg());
        sms.setBizNo(bizNo);
        smsMapper.insertSms(sms);
    }

    //钉钉群通知
    private void insertDdQunSms(SysTenantNotifyItem item, String sendMsg, String status, String remark, String bizNo) {
        Sms sms = new Sms();
        sms.setContent(sendMsg);
        sms.setStatus(status);
        sms.setTemplateId(5L);
        sms.setSendTime(new Date());
        sms.setCustomerName(item.getQyWebhook());
        sms.setTenantId(item.getTenantId());
        sms.setPushNode(item.getMsgType());
        sms.setRemark(remark);
        sms.setBizNo(bizNo);
        smsMapper.insertSms(sms);
    }

    //插入短信记录
    public void insertDxSms(String content, boolean msgFlag, String id, String name, Long tenantId, Integer type, String bizNo) {
        Sms sms = new Sms();
        sms.setContent(content);
        sms.setStatus(msgFlag ? "0" : "1");
        sms.setTemplateId(3L);
        sms.setSendTime(new Date());
        sms.setCustomerId(id);
        sms.setCustomerName(name);
        sms.setTenantId(tenantId);
        sms.setPushNode(type);
        sms.setBizNo(bizNo);
        smsMapper.insertSms(sms);
    }
}
